package com.csxh.web.pager.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.scan.JarFileUrlJar;

import com.csxh.web.pager.bean.Pager;
import com.csxh.web.pager.service.PagerService;
import com.csxh.web.util.StringUtil;
import com.csxh.web.util.WebUtil;

/**
 * Servlet implementation class PagerServlet
 */
@WebServlet("/pager.servlet")
public class PagerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PagerServlet() {
        super();
        // TODO Auto-generated constructor stub
        JarFileUrlJar url;
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//获取分页参数
		String className=Pager.parsePagerDataClassName(request.getParameterMap());
		if(StringUtil.isEmpty(className)){
			return;
		}
		
		Class<?> beanClazz=null;
		//判断是否有可以创建分页数据对象
		try {
			beanClazz= Class.forName(className);
		} catch (Exception e) {
			log(e.getMessage());
			return;
		}
        
		Integer pagerIndex=Pager.parsePagerIndex(request.getParameterMap(), 1);
		Integer pagerSize=Pager.parsePagerSize(request.getParameterMap(), 3);
		String whereClase=Pager.parseWhereClase(request.getParameterMap());
		Object[] params=Pager.parseWhereParams(request.getParameterMap());
		String showJsp=Pager.parseShowJsp(request.getParameterMap(),"#");
		
		//获取分页对象
		PagerService service=new PagerService();
		Pager<?> pager=service.findPager(beanClazz, pagerSize, pagerIndex, whereClase, params);
		//将请求参数传给分页对象
		pager.setPageIndex(pagerIndex);
		pager.setPageSize(pagerSize);
		pager.setWhereClase(whereClase);
		pager.setBeanClassName(className);
		pager.setWhereParams(params);
		pager.setShowJsp(showJsp);
		
		//保存到上下文中，以便在JSP页面上使用EL表达式获取
		request.setAttribute(WebUtil.PAGER, pager);
		
		
		
	}

}
